package com.example.administrator.newxlmedical;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.administrator.baseproject.BaseActivity;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

import adapters.SearchAdapter;
import beans.GoodsInfoBean;
import beans.ItemEntity;
import beans.PutAndDeleteBean;
import beans.StorageWarningBean;
import beans.StorageWarningInfoBean;
import beans.TerminalBean;
import beans.WarningInfoBean;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import constants.HandlerConstant;
import customhandler.MyHandler;
import dialogs.GoodsDetialsDialog;
import interfaces.MyItemClickListener;
import netframe.GetRetrofit;
import netframe.IFuzzySearchRule;
import netframe.NetAddress;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import singleton.SingletonClass;
import utils.ActivityUtil;
import utils.DefaultFuzzySearchRule;
import utils.FuzzySearchUtils;
import utils.ScreenUtils;
import utils.StockWarnSortUtils;
import utils.TimeUtil;
import utils.ToastUtil;
import utils.ViewUtil;

import static android.widget.AbsListView.OnScrollListener.SCROLL_STATE_IDLE;


public class SearchActivity extends BaseActivity {
    @BindView(R.id.rv_search_activity)
    RecyclerView recyclerView;
    @BindView(R.id.rl_search_empty)
    FrameLayout flEmpty;
    @BindView(R.id.et_search_material_name)
    EditText etMaterialName;
    @BindView(R.id.tv_search_activity_search)
    TextView tvSearch;
    @BindView(R.id.iv_common_toolbar_home)
    ImageView ivCommonToolbarHome;
    @BindView(R.id.remind_goods)
    TextView tvGoods;
    @BindView(R.id.iv_warn_set_goods_sort)
    ImageView ivGoodsSort;
    @BindView(R.id.rl_warn_set_goods_sort)
    RelativeLayout rlGoodsSort;
    @BindView(R.id.remind_supplier)
    TextView tvSupplier;
    @BindView(R.id.iv_warn_set_supplier_sort)
    ImageView ivSupplierSort;
    @BindView(R.id.rl_warn_set_supplier_sort)
    RelativeLayout rlSupplierSort;
    @BindView(R.id.remind_size)
    TextView tvSpecification;
    @BindView(R.id.iv_warn_set_specification_sort)
    ImageView ivSpecificationSort;
    @BindView(R.id.rl_warn_set_specification_sort)
    RelativeLayout rlSpecificationSort;
    @BindView(R.id.remind_count)
    TextView tvNumber;
    @BindView(R.id.iv_warn_set_number_sort)
    ImageView ivNumberSort;
    @BindView(R.id.rl_warn_set_number_sort)
    RelativeLayout rlNumberSort;
    @BindView(R.id.remind_data_end)
    TextView tvWarn;
    @BindView(R.id.iv_warn_set_warn_sort)
    ImageView ivWarnSort;
    @BindView(R.id.rl_warn_set_warn_sort)
    RelativeLayout rlWarnSort;

    private List<StorageWarningInfoBean> warnList = new ArrayList<>();
    private List<StorageWarningInfoBean> searchList = new ArrayList<>();
    private List<WarningInfoBean.DataBean> allList = new ArrayList<>();
    private List<StorageWarningInfoBean> llllllist = new ArrayList<>();
    private List<WarningInfoBean.DataBean> data = new ArrayList<>();
    private SearchAdapter adapter;
    private int lastLoadDataItemPosition;
    private int pageIndex = 0;
    private boolean isSortGoods, isSortSpecification, isSortSupplier, isSortNumber, isSortWarn;
    private int sortGoods, sortSpecification, sortSupplier, sortNumber, sortWarn;

    private SharedPreferences sharedPreferences;
    private StringBuilder sbUserIds = new StringBuilder();
    private StringBuilder sbGoodsIds = new StringBuilder();

    private StringBuilder sbGoodsIdsNow = new StringBuilder();

    private String goodsId;
    private int size;
    private boolean isLoadMore = true;
    private boolean isShowToast = true;
    private IFuzzySearchRule mIFuzzySearchRule;
    private FuzzySearchFilter fuzzySearchFilter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
        mIFuzzySearchRule = new DefaultFuzzySearchRule();
        fuzzySearchFilter = new FuzzySearchFilter();
    }

    @Override
    public void initView() {
        super.initView();
        showLoadingView(flEmpty);
        allHandler = SingletonClass.getSingleton(MyHandler.class);
        sharedPreferences = ActivityUtil.getSharedPreferences(this);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(manager);
        adapter = new SearchAdapter(SearchActivity.this, warnList);
        recyclerView.setAdapter(adapter);
        postData();
    }

    @Override
    protected void setListener() {
        super.setListener();
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (isLoadMore) {
                    if (newState == SCROLL_STATE_IDLE && lastLoadDataItemPosition == adapter.getItemCount()) {
                        showLoadingView(flEmpty);
                        size = pageIndex + 30;
                        int count = allList.size() - size;
                        sbUserIds.delete(0, sbUserIds.length());
                        if (count >= 0) {
                            sort(0);
                            for (int i = pageIndex; i < size; i++) {
                                WarningInfoBean.DataBean dataBean = allList.get(i);
                                sbUserIds.append("'" + dataBean.getGID() + "',");
                                StorageWarningInfoBean bean = new StorageWarningInfoBean();
                                bean.setGoodsName(dataBean.getGoodName());
                                bean.setNumber(dataBean.getCount() + "");
                                bean.setUnit(dataBean.getGoodsUnit());
                                bean.setSupplier(dataBean.getManufacturer());
                                bean.setSpecification(dataBean.getSpecification());
                                bean.setWarnCount(dataBean.getWarnCount()+"");
                                bean.setGID(dataBean.getGID() + "");
                                warnList.add(bean);
                                llllllist.add(bean);
                            }
                            pageIndex += 30;

                        } else {
                            int num = allList.size() - pageIndex;
                            if (num > 0) {
                                sort(0);
                                for (int i = pageIndex; i < allList.size(); i++) {
                                    WarningInfoBean.DataBean dataBean = allList.get(i);
                                    sbUserIds.append("'" + dataBean.getGID() + "',");
                                    StorageWarningInfoBean bean = new StorageWarningInfoBean();
                                    bean.setGoodsName(dataBean.getGoodName());
                                    bean.setNumber(dataBean.getCount() + "");
                                    bean.setUnit(dataBean.getGoodsUnit());
                                    bean.setSupplier(dataBean.getManufacturer());
                                    bean.setSpecification(dataBean.getSpecification());
                                    bean.setWarnCount(dataBean.getWarnCount()+"");
                                    bean.setGID(dataBean.getGID() + "");
                                    warnList.add(bean);
                                    llllllist.add(bean);
                                    searchList.add(bean);
                                }
                                pageIndex += num;
                            } else {
                                hideLoadingView();
                                if (isShowToast) {
                                    isShowToast = false;
                                    isLoadMore = false;
                                    ToastUtil.showToast(SearchActivity.this, "已加载全部!");
                                }
                            }
                        }
                        hideLoadingView();
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                if (layoutManager instanceof LinearLayoutManager) {
                    LinearLayoutManager manager = (LinearLayoutManager) layoutManager;
                    int lastVisibleItem = manager.findLastCompletelyVisibleItemPosition();
                    lastLoadDataItemPosition = lastVisibleItem + 1;
                }
            }
        });

        adapter.setItemClickListener(new MyItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {

                StorageWarningInfoBean bean = warnList.get(position);

                String name = bean.getGoodsName();
                String specification = "规格  :  " + bean.getSpecification();
                String supplier = "供应商  :  " + bean.getSupplier();
                String count = "单位  :  " + bean.getUnit();
                String operator = "数量  :  " + bean.getNumber();
                String time = "预警  :  " + bean.getWarnCount();

                String[] content = {name, specification, supplier, count, operator, time, "", ""};
                GoodsDetialsDialog dialog = new GoodsDetialsDialog(SearchActivity.this, R.style.dialog, content);

                dialog.show();
//                ActivityUtil.jumpToActivity(SearchActivity.this,GoodsDetialActivity.class);
            }
        });

        etMaterialName.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId== EditorInfo.IME_ACTION_SEARCH ||(event!=null&&event.getKeyCode()== KeyEvent.KEYCODE_ENTER)){
                    sort(0);
                    ScreenUtils.closeKeybord(etMaterialName, SearchActivity.this);
                    search();
                    return true;
                }

                return false;
            }
        });

    }

    // 获取柜子中的物品
    private void postData() {
//        String depatmentCode = sharedPreferences.getString(Constants.DEPARTMENT_CODE, "");
        String depatmentCode = NetAddress.deptCode;
//        ToastUtil.showToast(this,"depatmentCode = "+depatmentCode +"  token = "+NetAddress.token +"  machineCode = " + NetAddress.machineCode );
        Log.e(TAG, "postData: " + depatmentCode);
        GetRetrofit.getInstance().getWarningGoods(NetAddress.token, NetAddress.machineCode, NetAddress.deptCode)
                .enqueue(new Callback<WarningInfoBean>() {
                    @Override
                    public void onResponse(Call<WarningInfoBean> call, Response<WarningInfoBean> response) {
                        warnList.clear();
                        WarningInfoBean body = response.body();
                        if (body != null) {
                            data = body.getData();
//                            Toast.makeText(SearchActivity.this, "datasize = " + data.size(), Toast.LENGTH_SHORT);
                            sbUserIds.delete(0, sbUserIds.length());
                            sbGoodsIds.delete(0,sbGoodsIds.length());
                            sbGoodsIdsNow.delete(0,sbGoodsIdsNow.length());
                            if (data != null && data.size() != 0) {

                                contrastData(data);

                            } else {
                                hideLoadingView();
                                showEmptyView(flEmpty);
                            }

                        } else {
                            hideLoadingView();
                            showEmptyView(flEmpty);
                        }
                    }

                    @Override
                    public void onFailure(Call<WarningInfoBean> call, Throwable t) {
                        ToastUtil.showToast(SearchActivity.this, "postData:  " + t.getMessage());
                        hideLoadingView();
                        showEmptyView(flEmpty);
                    }
                });
    }

    // 跟数据库里对比 （数据库中存在该物品 修改数量，不存在 写入数据库）
    private void contrastData(final List<WarningInfoBean.DataBean> data) {

        GetRetrofit.getInstance().getStorageWarning(NetAddress.token, NetAddress.machineCode, "select * from StorageWarning where TerminalInfoId =" + NetAddress.terminalInfoId)
                .enqueue(new Callback<List<StorageWarningBean>>() {
                    @Override
                    public void onResponse(Call<List<StorageWarningBean>> call, Response<List<StorageWarningBean>> response) {
                        List<StorageWarningBean> body = response.body();
                        List<WarningInfoBean.DataBean> postData = new ArrayList<>();
                        if (body != null && body.size() != 0) {
                            for (int i = 0; i < data.size(); i++) {
                                int count = 0;
                                WarningInfoBean.DataBean dataBean = data.get(i);
                                sbGoodsIdsNow.append("'" + dataBean.getGID() + "',");
                                for (int j = 0; j < body.size(); j++) {
                                    StorageWarningBean warningBean = body.get(j);
                                    // goodsId相同
                                    if (warningBean.getGoodsInfoId() == dataBean.getGID()) {
                                        count++;
                                        // 数量不同
                                        if (warningBean.getStorageCount() != dataBean.getCount()) {
                                            update(dataBean.getCount() + "", dataBean.getGID() + "",1);
                                        }
                                        break;
                                    }
                                }
                                // count=0 代表有新数据
                                if (count == 0) {
                                    postData.add(dataBean);
                                }
                            }
                            sbGoodsIdsNow.deleteCharAt(sbGoodsIdsNow.length()-1);
                            update("","",2);
                            post(postData);

                        } else {
                            post(data);
                        }
                    }

                    @Override
                    public void onFailure(Call<List<StorageWarningBean>> call, Throwable t) {
                        Log.e("aa", "失败");
                        ToastUtil.showToast(SearchActivity.this, "contrastData:  " + t.getMessage());
                    }
                });

    }

    private void update(String count, String id ,int type) {
        String sql;
        if (type == 1){
            Log.e(TAG, "update: " );
            sql = "set StorageCount = " + count + " where GoodsInfoId = " + id + " and TerminalInfoId = " + NetAddress.terminalInfoId;
        }else {
            Log.e(TAG, "update11111111: " + sbGoodsIdsNow.toString());
            sql = "set StorageCount = 0 where GoodsInfoId not in (" +(sbGoodsIdsNow) + ") and TerminalInfoId = " + NetAddress.terminalInfoId ;
        }
        GetRetrofit.getInstance().putStorageWarningInfo(NetAddress.token, NetAddress.machineCode, sql)
                .enqueue(new Callback<PutAndDeleteBean>() {
                    @Override
                    public void onResponse(Call<PutAndDeleteBean> call, Response<PutAndDeleteBean> response) {
                        PutAndDeleteBean body = response.body();
                        if (body != null) {
                            Log.e("aaa", "修改成功");
//                            ToastUtil.showToast(SearchActivity.this, "修改成功");
                        } else {
//                            ToastUtil.showToast(SearchActivity.this, "修改失败");
                        }
                    }

                    @Override
                    public void onFailure(Call<PutAndDeleteBean> call, Throwable t) {

                    }
                });
    }

    private void post(List<WarningInfoBean.DataBean> dataBeans) {

        String nowTime = TimeUtil.getMillisecondDate();
        List<StorageWarningBean> list = new ArrayList<>();
        for (int i = 0; i < dataBeans.size(); i++) {
            StorageWarningBean bean = new StorageWarningBean();
            bean.setWarningCount(0);
            bean.setTerminalInfoId(Integer.parseInt(NetAddress.terminalInfoId));
            bean.setGoodsInfoId(dataBeans.get(i).getGID());
            bean.setSubTime(nowTime.substring(0, 10));
            bean.setDeleteFlag(false);
            bean.setStorageCount(dataBeans.get(i).getCount());
            list.add(bean);
        }

        if (list.size() != 0) {
            // 提交到数据库
            GetRetrofit.getInstance().postStorageWarning(NetAddress.token, NetAddress.machineCode, list)
                    .enqueue(new Callback<PutAndDeleteBean>() {
                        @Override
                        public void onResponse(Call<PutAndDeleteBean> call, Response<PutAndDeleteBean> response) {

                        }

                        @Override
                        public void onFailure(Call<PutAndDeleteBean> call, Throwable t) {
                            getData();
                        }
                    });
        } else {
            getData();
        }

    }
    // 获取数据中的预警值
    private void getData() {
        showLoadingView(flEmpty);

        GetRetrofit.getInstance().getStorageWarning1(NetAddress.token, NetAddress.machineCode, "select * from StorageWarning where TerminalInfoId =" + NetAddress.terminalInfoId)
                .enqueue(new Callback<List<StorageWarningBean>>() {
                    @Override
                    public void onResponse(Call<List<StorageWarningBean>> call, Response<List<StorageWarningBean>> response) {
                        List<StorageWarningBean> body = response.body();
//                        ToastUtil.showToast(SearchActivity.this, "body = " + response.code());

                        if (body != null && body.size() > 0) {
                            ToastUtil.showToastlog(SearchActivity.this,"StorageWarning Size  "+body.size()+"");
                            Log.e(TAG, "onResponse: " + body.size());
                            for (int i = 0; i < body.size(); i++) {
                                StorageWarningBean warningBean = body.get(i);
                                sbGoodsIds.append("'" + warningBean.getGoodsInfoId() + "',");
                                WarningInfoBean.DataBean newBean = new WarningInfoBean.DataBean();
                                newBean.setGID(warningBean.getGoodsInfoId());
                                newBean.setWarnCount(warningBean.getWarningCount());
                                newBean.setCount(warningBean.getStorageCount());
                                allList.add(newBean);
                            }

                            if (sbGoodsIds.length() > 0) {
                                sbGoodsIds.deleteCharAt(sbGoodsIds.length() - 1);
                            }

                            getDatas();

                        } else {
                            hideLoadingView();
                            showEmptyView(flEmpty);
                        }

                    }

                    @Override
                    public void onFailure(Call<List<StorageWarningBean>> call, Throwable t) {
                        ToastUtil.showToast(SearchActivity.this, "getdata  : " + t.getMessage());
                    }
                });
    }

    private void getDatas() {
        GetRetrofit.getInstance()
                .getGoodsInfo1(NetAddress.token, NetAddress.machineCode, "select * from GoodsInfo where ID in (" + sbGoodsIds.toString() + ")")
                .enqueue(new Callback<ArrayList<GoodsInfoBean>>() {
                    @Override
                    public void onResponse(Call<ArrayList<GoodsInfoBean>> call, Response<ArrayList<GoodsInfoBean>> response) {
                        hideLoadingView();
                        ArrayList<GoodsInfoBean> body = response.body();
                        if (body != null && body.size() != 0) {

                            for (int i = 0; i < allList.size(); i++) {
                                WarningInfoBean.DataBean dataBean = allList.get(i);
                                for (int j = 0; j < body.size(); j++) {
                                    GoodsInfoBean bean = body.get(j);
                                    if (bean.getID() == dataBean.getGID()) {
                                        allList.get(i).setGoodName(bean.getGoodName());
                                        allList.get(i).setGoodsUnit(bean.getGoodsUnit());
                                        allList.get(i).setManufacturer(bean.getManufacturer());
                                        allList.get(i).setSpecification(bean.getSpecification());
                                        break;
                                    }
                                }
                            }

                            int count;
                            if (allList.size() >= 30) {
                                count = 30;
                            } else {
                                count = allList.size();
                            }

                            for (int i = 0; i < count; i++) {
                                WarningInfoBean.DataBean dataBean = allList.get(i);
                                StorageWarningInfoBean showBean = new StorageWarningInfoBean();
                                showBean.setGID(dataBean.getGID() + "");
                                showBean.setWarnCount(dataBean.getWarnCount() + "");
                                showBean.setSpecification(dataBean.getSpecification());
                                showBean.setSupplier(dataBean.getManufacturer());
                                showBean.setUnit(dataBean.getGoodsUnit());
                                showBean.setNumber(dataBean.getCount() + "");
                                showBean.setGoodsName(dataBean.getGoodName());
                                warnList.add(showBean);
                                llllllist.add(showBean);
                                searchList.add(showBean);

                            }
                            pageIndex += count;
                            StockWarnSortUtils.sortWarnGoods(warnList, true);
                            adapter.notifyDataSetChanged();

                        } else {

                            showEmptyView(flEmpty);
                        }
                    }

                    @Override
                    public void onFailure(Call<ArrayList<GoodsInfoBean>> call, Throwable t) {

                    }
                });
    }

    private void search() {
        ScreenUtils.closeKeybord(etMaterialName,this);
        sort(0);
        hideEmptyView();
        String name = etMaterialName.getText().toString().trim();
        if (allList.size() != 0) {
            if (!TextUtils.isEmpty(name)) {
                isLoadMore = false;
                searchData(name);
            } else {
                warnList.clear();
                warnList.addAll(llllllist);
                searchList.clear();
                searchList.addAll(llllllist);
                isLoadMore = true;
                recyclerView.setVisibility(View.VISIBLE);
                adapter.notifyDataSetChanged();
            }
        } else {
            showEmptyView(flEmpty);
        }
        Log.e(TAG, "search: " + warnList.size());
    }

    private void searchData(String goodsName) {
        isLoadMore = false;
        showLoadingView(flEmpty);
        if (!TextUtils.isEmpty(goodsName)) {
            warnList.clear();
            searchList.clear();
            sbUserIds.delete(0, sbUserIds.length());

            fuzzySearchFilter.filter(goodsName);
        } else {
            hideLoadingView();
        }
    }

    private void searchDataToId() {
        GetRetrofit.getInstance().getStorageWarning(NetAddress.token, NetAddress.machineCode, "select * from StorageWarning where GoodsInfoId in (" + goodsId + ") and TerminalInfoId =" + NetAddress.terminalInfoId)
                .enqueue(new Callback<List<StorageWarningBean>>() {
                    @Override
                    public void onResponse(Call<List<StorageWarningBean>> call, Response<List<StorageWarningBean>> response) {
                        hideLoadingView();
                        List<StorageWarningBean> body = response.body();
                        if (body != null && body.size() > 0) {
                            for (int i = 0; i < body.size(); i++) {
                                StorageWarningBean warningBean = body.get(i);
                                warnList.get(i).setWarnCount(warningBean.getWarningCount() + "");
                            }
                            recyclerView.setVisibility(View.VISIBLE);
                            adapter.notifyDataSetChanged();
                        } else {

//                            ToastUtil.showToast(SearchActivity.this,"getdata null");
                            showEmptyView(flEmpty);
                        }
                    }

                    @Override
                    public void onFailure(Call<List<StorageWarningBean>> call, Throwable t) {

                    }
                });
    }

    @OnClick({R.id.tv_search_activity_search, R.id.iv_common_toolbar_home, R.id.rl_warn_set_goods_sort, R.id.rl_warn_set_supplier_sort,
            R.id.rl_warn_set_specification_sort, R.id.rl_warn_set_number_sort, R.id.rl_warn_set_warn_sort})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_search_activity_search:
                search();
                break;
            case R.id.iv_common_toolbar_home:
                finish();
                break;
            case R.id.rl_warn_set_goods_sort:
                sort(1);
                break;
            case R.id.rl_warn_set_supplier_sort:
                sort(2);
                break;
            case R.id.rl_warn_set_specification_sort:
                sort(3);
                break;
            case R.id.rl_warn_set_number_sort:
                sort(4);
                break;
            case R.id.rl_warn_set_warn_sort:
                sort(5);
                break;
        }
    }

    private void sort(int type) {
        if (type == 1) { // 按物品名排序
            if (sortGoods != 2) {
                isSortGoods = !isSortGoods;
                sortGoods++;
                StockWarnSortUtils.sortWarnGoods(warnList, isSortGoods);
            } else {
                clearSortDate();
                warnList.clear();
                warnList.addAll(searchList);
            }
        } else {
            sortGoods = 0;
            isSortGoods = false;
        }

        if (type == 2) { // 按供应商排序
            if (sortSupplier != 2) {
                sortSupplier++;
                isSortSupplier = !isSortSupplier;
                StockWarnSortUtils.sortWarnSupplier(warnList, isSortSupplier);
            } else {
                clearSortDate();
                warnList.clear();
                warnList.addAll(searchList);
            }
        } else {
            sortSupplier = 0;
            isSortSupplier = false;
        }

        if (type == 3) {
            if (sortSpecification != 2) {
                sortSpecification++;
                isSortSpecification = !isSortSpecification;
                StockWarnSortUtils.sortWarnSpecification(warnList, isSortSpecification);
            } else {
                clearSortDate();
                warnList.clear();
                warnList.addAll(searchList);
            }
        } else {
            sortSpecification = 0;
            isSortSpecification = false;
        }

        if (type == 4) {
            if (sortNumber != 2) {
                sortNumber++;
                isSortNumber = !isSortNumber;
                StockWarnSortUtils.sortWarnNumber(warnList, isSortNumber);
            } else {
                clearSortDate();
                warnList.clear();
                warnList.addAll(searchList);
            }
        } else {
            sortNumber = 0;
            isSortNumber = false;
        }

        if (type == 5) {
            if (sortWarn != 2) {
                sortWarn++;
                isSortWarn = !isSortWarn;
                StockWarnSortUtils.sortWarn(warnList, isSortWarn);
            } else {
                clearSortDate();
                warnList.clear();
                warnList.addAll(searchList);
            }
        } else {
            sortWarn = 0;
            isSortWarn = false;
        }

        ViewUtil.setSortColor(this, tvGoods, ivGoodsSort, sortGoods);
        ViewUtil.setSortColor(this, tvSupplier, ivSupplierSort, sortSupplier);
        ViewUtil.setSortColor(this, tvSpecification, ivSpecificationSort, sortSpecification);
        ViewUtil.setSortColor(this, tvNumber, ivNumberSort, sortNumber);
        ViewUtil.setSortColor(this, tvWarn, ivWarnSort, sortWarn);

        adapter.notifyDataSetChanged();
    }

    private void clearSortDate() {
        sortGoods = 0;
        sortSupplier = 0;
        sortWarn = 0;
        sortSpecification = 0;
        sortNumber = 0;
    }

    private class FuzzySearchFilter extends Filter {

        /**
         * 执行过滤操作,如果搜索的关键字为空，默认所有结果
         */

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {

            List<ItemEntity> dateList = FuzzySearchUtils.fillWarnData(allList);
            FilterResults result = new FilterResults();
            List<ItemEntity> filterList = new ArrayList<>();
            for (ItemEntity item : dateList) {
                if (mIFuzzySearchRule.accept(constraint, item.getSourceKey(), item.getFuzzyKey())) {
                    filterList.add(item);
                }
            }
            result.values = filterList;
            result.count = filterList.size();
            return result;
        }

        /**
         * 得到过滤结果
         */
        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            List<ItemEntity> mDataList = (List<ItemEntity>) results.values;
            if (mDataList != null && mDataList.size() != 0) {
                for (int i = 0; i < mDataList.size(); i++) {
                    Log.e("FFFF", "publishResults: " + mDataList.get(i).getmWarnBean().getGoodName());
                    WarningInfoBean.DataBean bean = mDataList.get(i).getmWarnBean();
                    sbUserIds.append("'" + bean.getGID() + "',");
                    StorageWarningInfoBean warningInfoBean = new StorageWarningInfoBean();
                    warningInfoBean.setGoodsName(bean.getGoodName());
                    warningInfoBean.setNumber(bean.getCount() + "");
                    warningInfoBean.setUnit(bean.getGoodsUnit());
                    warningInfoBean.setSupplier(bean.getManufacturer());
                    warningInfoBean.setSpecification(bean.getSpecification());
                    warningInfoBean.setWarnCount("0");
                    warningInfoBean.setGID(bean.getGID() + "");
                    warnList.add(warningInfoBean);
                }
            }
            sendEmptyMessage(HandlerConstant.FUZZY_SEARCH);
        }
    }

    @Override
    protected void onHandleMessage(Message msg) {
        super.onHandleMessage(msg);
        switch (msg.what){
            case HandlerConstant.FUZZY_SEARCH:
                if (warnList.size() != 0) {
                    searchList.addAll(warnList);
                    goodsId = sbUserIds.deleteCharAt(sbUserIds.length() - 1).toString();
                    searchDataToId();
                } else {
                    recyclerView.setVisibility(View.GONE);
                    showEmptyView(flEmpty);
                }
                hideLoadingView();
                break;
        }
    }
}